package Array;

//二分查找
public class binary_search {
    public static void main(String[] args) {
        search(new int[]{-1,0,3,5,9,12},9);
    }
    /*输入: nums = [-1,0,3,5,9,12], target = 9
       输出: 4
        解释: 9 出现在 nums 中并且下标为 4  */
    //左闭右闭写法：
    public static int search(int[] nums, int target) {
        //定义左右指针
        int left = 0;
        //注意这里是-1，而不是int right = nums.length； 不然超出索引
        int right = nums.length-1;
        while (left <= right) {
            //注意这里是left+(right - left) / 2; 而不是(right-left)/2，这里只是差值，而不是中间值
            int middle = left+(right - left) / 2;
            if (nums[middle] < target) {
                left = middle + 1;
            } else if (nums[middle] > target) {
                right = middle - 1;
            } else {
                //返回索引
                return middle;
            }
        }
        return -1;
    }
    //左闭右开
    public static int search_r(int[] nums, int target) {
        int left = 0;
        int right = nums.length-1;
        //区别1：这里因为right为开区间，不包含right
        while (left < right) {
            int middle = left+(right - left) / 2;
            if (nums[middle] < target) {
                left = middle + 1;
            } else if (nums[middle] > target) {
                //区别2：这里right应该给下一个区间去做边界
                right = middle;
            } else {
                //返回索引
                return middle;
            }
        }
        return -1;
    }
}
